#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <netinet/in.h>


static void *pkt_proc( void *arg )
{
	char buffer[256] = {0};
	int n = 0, ret = 0;
	unsigned int client_s = *( unsigned int * )arg; 

	
	bzero( buffer, 256 );
	
	n = read( client_s, buffer, 255 );	
	if ( n < 0 ) {
		printf( "Error reading from socket.\n" );
		return ;
	}
	
	printf( "%s.\n", buffer );
	n = write( client_s, "I got your message",18 );
	if ( n < 0 ) {
		printf( "Error reading from socket.\n" );
		return ;
	}

	close( client_s );

	return;
}

int main( int argc, char *argv[] ) 
{
	int sockfd, newsockfd, port;
	unsigned int ids = 0;
	socklen_t clilen;
	struct sockaddr_in serv_addr, cli_addr;
	pthread_t threads;
	int n = 0, ret = 0;

	sockfd = socket( AF_INET, SOCK_STREAM, 0 );	
	if ( sockfd < 0 ) {
		printf( "Create socket file failed.\n" );
		return -1;
	}

	bzero( ( void* )&serv_addr, sizeof( serv_addr ) );

	port = atoi( argv[1] );
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = INADDR_ANY;
	serv_addr.sin_port = htons( port );

	ret = bind( sockfd, ( struct sockaddr* )&serv_addr, sizeof( serv_addr ) );	
	if ( ret < 0 ) {
		printf( "Bind port failed for socket.\n" );
		return -1;
	}

	listen( sockfd, 100 );

	while ( 1 ) {
		clilen = sizeof( cli_addr );
		newsockfd = accept( sockfd, ( struct sockaddr* )&cli_addr,
				&clilen );
		if ( newsockfd < 0 ) {
			printf( "Accept failed.\n" );
			return -1;
		} else {
			ids = newsockfd;
			pthread_create( &threads, 
					NULL,	
					pkt_proc,
					&ids );

			pthread_join( threads, NULL );
		}

	}


	close( sockfd );

	return 0;
}
